<template>
  <div class="LogSearch">
    <el-row :gutter="10" class="linkShowSearchCondition">
      <el-col :span="6" style="width:500px;">
        <div style="width:70px;display:inline-block;">时间范围：</div>
        <el-date-picker v-model="timeRange" type="datetimerange" @blur="clearBlur" @change="timeRangeChange" :default-value="pickerValue" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size='small' value-format='yyyy-MM-dd HH:mm:ss' style="margin-bottom:10px;">
        </el-date-picker>
      </el-col>
      <el-col :span="6" style="width:350px;">
        <el-button type="success" size='small' @click="seniorListData(true)" style="margin-bottom:10px;">搜索</el-button>
        <el-button type="danger" size='small' @click="clearListData" style="margin-bottom:10px;">清空日志</el-button>
        <el-button type="text" id="closeSearchBtn" size='small' @click="showAll = !showAll" style="margin-bottom:10px;">
          {{word}}
          <i :class="showAll ? 'el-icon-arrow-up ': 'el-icon-arrow-down'"></i>
        </el-button>
      </el-col>
    </el-row>
    <collapseTransition name="slide-fade">
      <el-row :gutter="10" class="linkShowSearchCondition" id="searchBox" v-show="showAll">
        <el-col :span="6" style="width:350px;">
          <div style="width:70px;display:inline-block;">所属模块：</div>
          <el-select v-model="record.mode" filterable clearable placeholder="请选择" style="width:220px;margin-bottom:10px;" size='small'>
            <el-option v-for="item in modesList" :key="item.name" :label="item.chinese_name" :value="item.name">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" style="width:350px;">
          <div style="width:70px;display:inline-block;">级别：</div>
          <el-select v-model="record.level" filterable clearable placeholder="请选择" style="width:220px;margin-bottom:10px;" size='small'>
            <el-option v-for="(item, key) in levelList" :key="key" :label="item" :value="key">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" style="width:350px;">
          <div style="width:70px;display:inline-block;">源地址：</div>
          <el-input v-emoji v-model="record.srcIp" style="width:220px;margin-bottom:10px;" size='small'></el-input>
        </el-col>
        <el-col :span="6" style="width:350px;">
          <div style="width:70px;display:inline-block;">目的地址：</div>
          <el-input v-emoji v-model="record.dstIp" style="width:220px;margin-bottom:10px;" size='small'></el-input>
        </el-col>
        <el-col :span="6" style="width:350px;">
          <div style="width:70px;display:inline-block;">源端口：</div>
          <el-input v-emoji v-model="record.sport" style="width:220px;margin-bottom:10px;" size='small'></el-input>
        </el-col>
        <el-col :span="6" style="width:350px;">
          <div style="width:70px;display:inline-block;">目的端口：</div>
          <el-input v-emoji v-model="record.dport" style="width:220px;margin-bottom:10px;" size='small'></el-input>
        </el-col>
        <el-col :span="6" style="width:350px;">
          <div style="width:70px;display:inline-block;">事件类型：</div>
          <el-select v-model="record.eventType" filterable clearable placeholder="请选择" style="width:220px;margin-bottom:10px;" size='small'>
            <el-option v-for="item in eventTypeList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" style="width:350px;">
          <div style="width:70px;display:inline-block;">事件动作：</div>
          <el-select v-model="record.eventAction" filterable clearable placeholder="请选择" style="width:220px;margin-bottom:10px;" size='small'>
            <el-option v-for="item in eventActionList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6" style="width:350px;">
          <div style="width:70px;display:inline-block;">协议类型：</div>
          <el-select v-model="record.l4type" filterable clearable placeholder="请选择" style="width:220px;margin-bottom:10px;" size='small'>
            <el-option v-for="item in l4typeList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
    </collapseTransition>
    <el-table ref="multipleTable" size='mini' :data="tableList" :row-class-name="tableRowClassName" :row-key='getRowKey' @sort-change='sortChange' tooltip-effect="dark" style="width: 100%">
      <el-table-column prop="TIME" align='center' label="时间" sortable='custom' :formatter="timeFormatter" min-width="150"></el-table-column>
      <el-table-column prop="MODE" align='center' label="模块" min-width="120">
        <template slot-scope="scope">
          {{ modeListShow(scope.row.MODE) || '' }}
        </template>
      </el-table-column>
      <el-table-column prop="LEVEL" align='center' label="级别" sortable='custom' min-width="100">
        <template slot-scope="scope">
          {{ levelList[scope.row.LEVEL] || '' }}
        </template>
      </el-table-column>
      <el-table-column prop="MSG" align='center' label="信息" min-width="300">
        <template slot-scope="scope">
          <tooltip :copyText="scope.row.MSG" class="wid190">
          </tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="SIP" align='center' label="源地址" min-width="120">
        <template slot-scope="scope">
          <tooltip :copyText="scope.row.SIP" class="wid190">
          </tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="DIP" align='center' label="目的地址" min-width="120">
        <template slot-scope="scope">
          <tooltip :copyText="scope.row.DIP" class="wid190">
          </tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="SPORT" align='center' label="源端口" min-width="100"></el-table-column>
      <el-table-column prop="DPORT" align='center' label="目的端口" min-width="100"></el-table-column>
      <el-table-column prop="L4TYPE" align='center' label="协议类型" min-width="100"></el-table-column>
      <el-table-column prop="EVENT_TYPE" align='center' label="事件类型" min-width="100">
        <template slot-scope="scope">
          <tooltip :copyText="scope.row.EVENT_TYPE || '其他'" class="wid190">
          </tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="EVENT_ACTION" align='center' label="事件动作" min-width="100">
        <template slot-scope="scope">
          {{ actionsList[scope.row.EVENT_ACTION] || scope.row.EVENT_ACTION }}
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="record.page" :page-size="record.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
  </div>
</template>

<script>
// import { sessionSearch, advancedSearch, getEvent, getMode } from '@/api/system/logData'
import { cleanDpLog, advancedSearch, getEvent, getMode } from '@/api/system/oldLogData'
import moment from 'moment'
export default {
  name: 'LogSearch',
  data () {
    return {
      record: {
        timeRange: '',
        mode: '',
        level: '',
        srcIp: '',
        dstIp: '',
        eventType: '',
        eventAction: '',
        sport: '',
        dport: '',
        l4type: '',
        FIELD: '',
        ORDERTYPE: '',
        page: 1,
        limit: 20
      },
      recordCopy: {
        timeRange: '',
        mode: '',
        level: '',
        srcIp: '',
        dstIp: '',
        eventType: '',
        eventAction: '',
        sport: '',
        dport: '',
        l4type: '',
        FIELD: '',
        ORDERTYPE: '',
        page: 1,
        limit: 20
      },
      showAll: false,
      timeRange: null,
      loading: false,
      total: 0,
      tableList: [],
      onIndex: null,
      levelList: {
        '1': 'ERROR',
        '2': 'ALERT',
        '3': 'INFO',
        '4': 'DEBUG'
      },
      actionsList: {
        'DROP': '丢弃',
        'REJECT': '拒绝',
        'SE': '安全引擎',
        'ACCEPT': '允许'
      },
      modesList: null,
      eventTypeList: [],
      eventActionList: [],
      l4typeList: [],
      pickerMinDate: '',
      sortList: {
        'descending': 'desc',
        'ascending': 'asc'
      },
      pickerValue: [new Date().getTime() - 3600 * 1000 * 24 * 30, new Date().getTime()],
      pickerOptions: {
        onPick: (obj) => {
          if (this.pickerMinDate === '') {
            this.pickerMinDate = new Date(obj.minDate).getTime()
          } else {
            this.pickerMinDate = ''
          }
        },
        disabledDate: (time) => {
          if (this.pickerMinDate) {
            const day1 = 10 * 24 * 3600 * 1000 - 1
            let maxTime = this.pickerMinDate + day1
            let minTime = this.pickerMinDate - day1
            return time.getTime() > maxTime || time.getTime() < minTime || time.getTime() > Date.now()
          } else {
            // return time.getTime() > Date.now() + 0 * 24 * 3600 * 1000
            return time.getTime() > new Date()
          }
        },
        // disabledDate: (time) => {
        //   return time.getTime() > new Date()
        // },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            const end = new Date()
            const start = new Date(moment(new Date()).format('YYYY-MM-DD 00:00:00'))
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三天',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  computed: {
    word: function () {
      if (this.showAll === false) {
        // 对文字进行处理
        return '展开搜索'
      } else {
        return '收起搜索'
      }
    }
  },
  created () {
    getEvent().then(res => {
      if (res.status === 0) {
        this.eventTypeList = res.info.event_type
        this.eventActionList = res.info.event_action
        this.l4typeList = res.info.l4type
      }
    })
    getMode().then(res => {
      if (res.status === 0) {
        this.modesList = res.info
      }
    })
    this.seniorListData()
  },
  methods: {
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.record.limit = val
      this.record.page = 1
      this.seniorListData()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.record.page = val
      this.seniorListData()
    },
    seniorListData (flag) {
      // this.loading = true
      if (flag) {
        this.record.page = 1
      }
      advancedSearch(this.record).then(res => {
        if (res.status === 0) {
          this.tableList = res.info.data
          this.total = res.info.count
        }
      })
    },
    timeFormatter (data) {
      return moment(new Date(data.TIME) * 1000).format('YYYY-MM-DD HH:mm:ss')
    },
    timeRangeChange () {
      if (this.timeRange && this.timeRange.length > 0) {
        if (((new Date(this.timeRange[1]).getTime() - new Date(this.timeRange[0]).getTime()) / 1000 / 3600 / 24) > 10) {
          this.$message({
            message: '最多选择10天时间范围',
            type: 'error'
          })
          this.timeRange[1] = moment(new Date(this.timeRange[0]).getTime() + 24 * 3600 * 1000 * 10).format('YYYY-MM-DD HH:mm:ss')
        }
        this.record.timeRange = this.timeRange[0] + '~' + this.timeRange[1]
      } else {
        this.record.timeRange = ''
      }
    },
    clearBlur () {
      this.pickerMinDate = ''
    },
    sortChange (column, prop, order) {
      if (column.order) {
        this.record.FIELD = column.prop
        this.record.ORDERTYPE = this.sortList[column.order]
      } else {
        this.record.FIELD = ''
        this.record.ORDERTYPE = ''
      }
      this.seniorListData()
    },
    modeListShow (mode) {
      if (this.modesList) {
        return this.modesList.filter(item => item.name === mode)[0] ? this.modesList.filter(item => item.name === mode)[0].chinese_name : mode
      }
    },
    tableRowClassName ({ row, rowIndex }) {
      if (row.ID === this.onIndex) {
        return 'warning-row'
      }
      return ''
    },
    getRowKey (row) {
      return row.ID
    },
    clearListData () {
      this.$confirm('确定清空日志吗,清空日志需要一定时间！', '提示', {
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmButton',
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        cleanDpLog().then(res => {
          if (res.status === 0) {
            this.$messages.success('清空成功')
            if (res.info === 1) {
              let reg = new RegExp('(?<=http:\\/\\/|https:\\/\\/)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62}|(:[0-9]{1,6}))+\\.?', 'g')
              const hrefUrl = window.location.href.match(reg)
              let url = hrefUrl[0] + '/#/system/log/managelog'
              let path = window.location.protocol + '//' + url
              window.location.href = path
              window.location.reload()
            } else {
              this.listData()
            }
          }
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}
.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}
</style>
<style lang="less">
.LogSearch {
  .el-table .warning-row {
    background: rgb(95, 184, 120) !important;
    color: #fff;
  }
  .el-table .el-table__expanded-cell {
    background: #e6e6e6 !important;
  }
  /* 用来设置当前页面element全局table 鼠标移入某行时的背景色*/
  .el-table--enable-row-hover .el-table__body .warning-row:hover > td {
    background: rgb(95, 184, 120) !important;
  }
  .el-table--enable-row-hover .el-table__body .el-table__row:hover > td {
    color: #0033ff; /* 设置文字颜色，可以选择不设置 */
  }
}
</style>
